import unittest
import json
from pathlib import Path
from typing import Dict, Any
import time
import base64
from system_integration import CareerDevelopmentSystem
from agents.career_assessment import CareerAssessment
from agents.recruitment_portal import RecruitmentPortal
from mobile.mobile_adapter import MobileAdapter
from agents.knowledge_graph import JobKnowledgeGraph

# 测试配置
TEST_CONFIG = {
    "kafka_config": {
        "bootstrap_servers": "localhost:9092",
        "topic": "test_career_events"
    },
    "ray_config": {
        "num_cpus": 2
    }
}

class IntegratedSystemTest(unittest.TestCase):
    """全系统集成测试"""
    
    @classmethod
    def setUpClass(cls):
        """初始化测试环境"""
        cls.kg = JobKnowledgeGraph()
        cls.system = CareerDevelopmentSystem(TEST_CONFIG)
        cls.assessor = CareerAssessment(cls.kg)
        cls.portal = RecruitmentPortal(cls.kg)
        cls.mobile = MobileAdapter(cls.kg)
        
        # 创建测试数据目录
        cls.test_data_dir = Path("b/tests/data")
        cls.test_data_dir.mkdir(parents=True, exist_ok=True)
        
        # 创建测试简历文件
        cls.test_resume = cls.test_data_dir / "sample_resume.pdf"
        with open(cls.test_resume, "w") as f:
            f.write("示例简历内容\n技能: Python, SQL")
    
    def test_full_user_journey(self):
        """测试用户全周期旅程"""
        # 1. 移动端上传简历
        with open(self.test_resume, "rb") as f:
            img_data = base64.b64encode(f.read()).decode("utf-8")
        
        mobile_result = self.mobile.process_image_upload(img_data)
        self.assertEqual(mobile_result["status"], "success")
        
        # 2. 职业测评
        test_answers = {
            "Q1": "独立安静的空间",
            "Q2": "解决复杂的技术问题",
            "Q3": "分析数据并发现规律"
        }
        assessment = self.assessor.conduct_assessment("test_user", test_answers)
        self.assertGreater(len(assessment.recommended_jobs), 0)
        
        # 3. 系统集成处理
        user_data = {
            "user_id": "test_user",
            "resume_file": str(self.test_resume),
            "target_job": assessment.recommended_jobs[0],
            "assessment_result": assessment.dimensions
        }
        journey_result = self.system.process_user_journey(user_data)
        
        # 验证各阶段输出
        self.assertIn("phases", journey_result)
        self.assertIn("job_recommendations", journey_result["phases"])
        
    def test_recruitment_workflow(self):
        """测试企业招聘全流程"""
        # 1. 创建职位
        job_data = {
            "title": "Senior Python Developer",
            "description": "负责核心系统开发...",
            "requirements": ["Python", "Django", "AWS"]
        }
        job = self.portal.create_job_posting(job_data)
        self.assertEqual(job.title, job_data["title"])
        
        # 2. 发布职位
        published_job = self.portal.publish_job(job.job_id)
        self.assertEqual(published_job.status, "published")
        
        # 3. 候选人申请
        candidate = self.portal.add_candidate({
            "resume_file": str(self.test_resume),
            "applied_jobs": [job.job_id]
        })
        self.assertIn(job.job_id, candidate.applied_jobs)
        
        # 4. 筛选候选人
        screening = self.portal.screen_candidate(candidate.candidate_id, job.job_id)
        self.assertGreaterEqual(screening["match_score"], 0)
        
        # 5. 安排面试
        interview, questions = self.portal.schedule_interview({
            "candidate_id": candidate.candidate_id,
            "job_id": job.job_id,
            "interviewers": ["hr@example.com"],
            "scheduled_time": "2023-12-20T10:00:00"
        })
        self.assertEqual(interview.job_id, job.job_id)
        
    def test_mobile_integration(self):
        """测试移动端集成"""
        # 1. 图片处理
        with open(self.test_resume, "rb") as f:
            img_data = base64.b64encode(f.read()).decode("utf-8")
        
        upload_result = self.mobile.process_image_upload(img_data)
        self.assertEqual(upload_result["status"], "success")
        
        # 2. 数据优化
        optimized = self.mobile.get_mobile_optimized_data(upload_result["result"])
        self.assertTrue(optimized["mobile_optimized"])
        
        # 3. 通知生成
        notification = self.mobile.generate_push_notification(
            "interview_scheduled",
            {"job_title": "Python Developer", "time": "2023-12-15 14:00"}
        )
        self.assertIn("Python Developer", notification["body"])
        
    def test_performance_benchmark(self):
        """性能基准测试"""
        test_cases = [
            {"type": "resume_upload", "data": str(self.test_resume)},
            {"type": "assessment", "answers": {"Q1": "A", "Q2": "B"}},
            {"type": "job_apply", "resume": str(self.test_resume)}
        ]
        
        results = []
        for case in test_cases:
            start_time = time.time()
            
            if case["type"] == "resume_upload":
                with open(case["data"], "rb") as f:
                    img_data = base64.b64encode(f.read()).decode("utf-8")
                self.mobile.process_image_upload(img_data)
                
            elif case["type"] == "assessment":
                self.assessor.conduct_assessment("perf_test", case["answers"])
                
            elif case["type"] == "job_apply":
                self.portal.add_candidate({"resume_file": case["resume"]})
                
            duration = time.time() - start_time
            results.append({"type": case["type"], "time": duration})
        
        # 输出性能报告
        print("\n性能测试结果:")
        for r in results:
            print(f"{r['type']}: {r['time']:.2f}s")
            
        # 验证性能指标
        self.assertTrue(all(r["time"] < 5.0 for r in results))
        
    @classmethod
    def tearDownClass(cls):
        """清理测试环境"""
        cls.test_resume.unlink()

if __name__ == "__main__":
    unittest.main()